package com.example.concurrentprogramming8016.ReentrantReadWriteLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author liyanhao
 * @Date 2023-01-07 15:12
 * 锁降级
 */
public class ReentrantReadWriteLockDemo2 {
    private final ReentrantReadWriteLock reentrantReadWriteLock
            = new ReentrantReadWriteLock();
    private final Lock readLock = reentrantReadWriteLock.readLock();
    private final Lock writeLock = reentrantReadWriteLock.writeLock();
    private volatile boolean update = false;
    public void processData(){
        readLock.lock();
        if (!update) {
            //必须先释放读锁
            System.out.println("先加读锁");
            readLock.unlock();
            //锁降级从写锁获取到开始
            writeLock.lock();
            try {
                if (!update) {
                    //todo 准备数据的流程
                    update = true;
                }
                readLock.lock();
            }finally {
                writeLock.unlock();
            }
        }
        //锁降级完成 写锁降级为读锁
        try {
            //todo 读取使用数据的流程
        }finally {
            readLock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockDemo2 reentrantReadWriteLockDemo2
                = new ReentrantReadWriteLockDemo2();
        reentrantReadWriteLockDemo2.processData();

    }
}
